import CryptoJS from "crypto-js";
import utils from './utils'

// let keyStr = 'qfaixha45a4s6a4a';// 密钥
let keyStr = utils.randomNumber();// 随机数
// 加密数据
export default {
	// 加密
	encrypt(word) {
		if (typeof word === 'object') {
			word = utils.objParseParam(word)
		}

		let key = CryptoJS.enc.Utf8.parse(keyStr);
		let srcs = CryptoJS.enc.Utf8.parse(word);
		let encrypted = CryptoJS.AES.encrypt(srcs, key, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		let appKey = encrypted.toString();//加密后的信息
		console.log(word, "我的传输");
		console.log(keyStr, "随机数");
		console.log(appKey, "======/加密后的信息", encodeURIComponent(appKey));
		let obj = {
			keyStr: keyStr,
			appKey: encodeURIComponent(appKey)
		}
		console.log(obj, "=============aes返回");
		return obj;
	},

	// 解密
	decrypt(word, keyStr) {
		let str = (word + '').replace(/\n*$/g, '').replace(/\n/g, ''); //增加这一行，将换行符替换为空
		var key = CryptoJS.enc.Utf8.parse(keyStr);
		var decrypt = CryptoJS.AES.decrypt(str, key, {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		try {
			console.log(decrypt, "aes解密");
			return CryptoJS.enc.Utf8.stringify(decrypt).toString(CryptoJS.enc.Utf8);
		} catch (error) {
			throw '解密错误' + error
		}
	}
};